import _ from 'lodash-es';
import { defineStore } from 'pinia';
import { getSystemDeptAll, getSystemPermissionAll, getSystemRoleAll } from '@/apis/api-system';

const useSystemStore = defineStore('storeSystem', {
  state: () => ({
    systemMenu: [], // 系统菜单
    systemDept: [], //组织数据
    systemRole: [], //系统所有角色
    systemPermission: [], //系统所有权限
    personalShow: false, //个人中心显示
    launchMenus: [], // 首页菜单
  }),

  actions: {
    // 存储个人中心显示状态
    SET_PERSONAL_SHOW(show) {
      this.personalShow = show;
    },
    // 存储系统所有权限
    STORE_SYSTEM_PERMISSION(permission) {
      this.systemPermission = permission;
    },
    // 存储系统所有角色
    STORE_SYSTEM_ROLE(role) {
      this.systemRole = role;
    },

    // 存储部门信息
    STORE_SYSTEM_DEPT(dept) {
      this.systemDept = dept;
    },

    // 存储系统菜单
    STORE_SYSTEM_MENU(menu) {
      this.systemMenu = menu;
    },

    // 存储首页菜单
    STORE_SYSTEM_LAUNCH_MENU(menu) {
      this.launchMenus = menu;
    },

    // 树形结构转换成一维数组
    getOneArr(arr) {
      let tree = _.cloneDeep(arr);
      let newData = {};

      const expanded = (datas) => {
        if (datas && datas.length > 0) {
          datas.forEach((e) => {
            newData[e.title] = false;
            expanded(e.children);
          });
        }
      };

      expanded(tree);
      this.STORE_SYSTEM_PERMISSION(newData);
    },

    // 处理数据递归出首页结构
    handleLaunchMenus(orgList) {
      const list = [];

      orgList.map((item) => {
        if (item.type == 4) return;
        list.push({
          menuTitle: item?.title,
          menuTabItems: item.children.length && item.children[0].type == 2 ? this.handleLaunchMenus(item.children) : [],
          menuPath: item?.description,
          code: item?.code,
          icon: item?.icon,
          route: item?.route,
          menuItems: item.children.length && item.children[0].type == 3 ? this.handleLaunchMenus(item.children) : [],
        });
      });

      return list;
    },

    // 获取所有菜单
    async getSystemPermissionAllApi() {
      try {
        const [err, data] = await getSystemPermissionAll();

        if (!err) {
          this.STORE_SYSTEM_MENU(data.data);

          const list = this.handleLaunchMenus(data.data);

          this.STORE_SYSTEM_LAUNCH_MENU(list);
          this.getOneArr(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 获取所有组织架构
    async getSystemDeptAllApi() {
      try {
        const [err, data] = await getSystemDeptAll();

        if (!err) {
          this.STORE_SYSTEM_DEPT(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // 获取所有角色
    async getSystemRoleAllApi() {
      try {
        const [err, data] = await getSystemRoleAll();

        if (!err) {
          this.STORE_SYSTEM_ROLE(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
});

export default useSystemStore;
